package com.ibiaoke.boss.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.ibiaoke.common.base.BaseController;
import com.ibiaoke.common.configs.AliPayConfigs;
import com.ibiaoke.common.consts.BusinessDef;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.customer.consts.PayTypeConst;
import com.ibiaoke.customer.service.FightGroupService;
import com.ibiaoke.customer.service.OpenGroupService;
import com.ibiaoke.order.entity.PtOrder;
import com.ibiaoke.order.service.PtOrderService;
import com.ibiaoke.pay.AppWXPayConfigImpl;
import com.ibiaoke.pay.WXPayConfigImpl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

import static java.util.stream.Collectors.joining;

@Controller
public class WxPtPayNotifyController extends BaseController {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Autowired
    private PtOrderService PtOrderService;

    @Autowired
    private OpenGroupService openGroupService;

    @Autowired
    private FightGroupService fightGroupService;

    @Autowired
    private PtOrderService ptOrderService;
    /**
     * 微信支付回调接口
     * @return
     */
    @RequestMapping("/wxPtPayNotify/{businessType}")
    public void wxPayNotify(@PathVariable String businessType, HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String dataXml = br.lines().collect(joining());
            Map<String, String> dataMap = WXPayUtil.xmlToMap(dataXml);
            //logger.info("微信支付回调 "+ JSONObject.toJSONString(dataMap));
            WXPay wxPay;
            if (businessType.equals("WX_Pt_PAY_ORDER") || businessType.equals(BusinessDef.WX_PAY_DEPOSIT)) {
                wxPay = new WXPay(new AppWXPayConfigImpl());
            }else {
                wxPay = new WXPay(new WXPayConfigImpl());
            }
            //判断是否是微信响应
            boolean valid = wxPay.isResponseSignatureValid(dataMap);
            if(valid){
                if(Objects.equals(dataMap.get("return_code"), WXPayConstants.SUCCESS)){
                    if(Objects.equals(dataMap.get("result_code"), WXPayConstants.SUCCESS)){
                        String out_trade_no = dataMap.get("out_trade_no");
                        String transaction_id = dataMap.get("transaction_id");
                        int result = 0;
                        //APP微信
                        if(Objects.equals(businessType, "WX_Pt_PAY_ORDER")) {
                            PtOrder ptOrder = PtOrderService.getPtOrderByCode(out_trade_no).get(0);
                            PtOrderService.updateOrderStatus(ptOrder);
                            result = PtOrderService.upPtOrderTransaction(ptOrder.getPtOrderId(),transaction_id);
                        }
                        //微商城--微信
                        if (Objects.equals(businessType, "Pt_PAY_ORDER")) {
                            logger.info("微信拼团交易成功，开始执行回调业务");
                            PtOrder ptOrder = PtOrderService.getPtOrderByCode(out_trade_no).get(0);
                            PtOrderService.updateOrderStatus(ptOrder);
                            result = PtOrderService.upPtOrderTransaction(ptOrder.getPtOrderId(),transaction_id);
                        }
                        if(result>0) {
                            PrintWriter writer = response.getWriter();
                            writer.print("<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>");
                            writer.close();
                        }
                    }
                }else{
                    dataMap.get("return_msg");
                }
            }
        } catch (Exception e) {
            throw new ServiceException("微信支付回调异常",e);
        }
    }

    /**
     * 支付宝回调接口
     * @param businessType
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/aliPtPayNotify/{businessType}")
    public void aliPayNotify(@PathVariable String businessType,HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AliPayConfigs.getAliPublicKey(), AliPayConfigs.CHARSET, AliPayConfigs.SIGNTYPE);

        if(verify_result){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if("TRADE_FINISHED".equals(trade_status)){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else if ("TRADE_SUCCESS".equals(trade_status)){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                int result = 0;
                if(Objects.equals(businessType, BusinessDef.Ali_Pt_PAY_ORDER)) {
                    logger.info("支付宝拼团交易成功，开始执行回调业务");
                    PtOrder ptOrder = PtOrderService.getPtOrderByCode(out_trade_no).get(0);
                    PtOrderService.updateOrderStatus(ptOrder);
                    result = PtOrderService.upPtOrderTransaction(ptOrder.getPtOrderId(),trade_no);
                }

                if(Objects.equals(businessType, BusinessDef.PAY_DEPOSIT)) {
                    //result=tradeRecorderService.depositChargeSuccess(out_trade_no,PayTypeConst.ALIPAY,trade_no);
                }
                if(result>0){
                    PrintWriter writer = response.getWriter();
                    writer.println("success");	//请不要修改或删除
                    writer.close();
                }
                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            }
        }
    }
}
